import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

# 读取数据并绘图
n_values = [2, 4, 6, 8]
plt.figure(figsize=(10, 8))

for n in n_values:
    data = pd.read_csv(f'data_B{n}.csv', header=None)  # 指定没有列标题
    plt.plot(data[0], data[1], label=f'n={n}')  # 使用列名（0和1）代替整数索引

# 绘制精确函数
x_exact = np.linspace(-5, 5, 400)
y_exact = 1 / (1 + x_exact**2)
plt.plot(x_exact, y_exact, 'k--', label='Exact function')

# 添加图例和标签
plt.legend()
plt.title('Problem B: Runge Phenomenon')
plt.xlabel('X')
plt.ylabel('f(X)')
plt.grid(True)
plt.savefig('B.png') 
plt.show()